var gulp = require("gulp"),
  minifycss = require("gulp-minify-css"),
  concat = require("gulp-concat"),
  uglify = require("gulp-uglify"),
  rename = require("gulp-rename"),
  jshint = require("gulp-jshint");
var map = require("map-stream");
var browserSync = require("browser-sync");
var reload = browserSync.reload;

// 监视文件改动并重新载入
gulp.task("start", function() {
  browserSync({ server: { baseDir: "client" } });

  gulp.watch(
    ["*.html", "styles/**/*.css", "scripts/**/*.js"],
    { cwd: "client" },
    reload
  );
});

var myReporter = map(function(data, cb) {
  if (!data.jshint.success) {
    console.log(
      "[ " +
        data.jshint.results.length +
        " errors in ]" +
        data.jshint.results[0].file
    );
    var errState = false;
    data.jshint.results.forEach(function(err) {
      if (!err.error.code || err.error.code != "W041") {
        console.log(
          err.error.code +
            "~~~" +
            err.file +
            "~~~" +
            err.error.line +
            "~~~" +
            err.error.character +
            "~~~" +
            err.error.reason
        );
        errState = true;
      }
    });
  }
  if (errState) data.jshint.success = true;
  cb(null, data);
});

//语法检查
gulp.task("jshint", function() {
  return gulp
    .src("./client/javascript/*.js")
    .pipe(jshint())
    .pipe(myReporter);
});
// 压缩css
gulp.task("minifycss", function() {
  return gulp
    .src("./client/styles/*.css") //需要操作的文件
    .pipe(minifycss()) //执行压缩
    .pipe(gulp.dest("./dist/styles")); //输出文件夹
});
//压缩，合并 js
gulp.task("minifyjs", function() {
  return gulp
    .src("./client/scripts/*.js") //需要操作的文件
    .pipe(uglify()) //压缩
    .pipe(gulp.dest("./dist/scripts")); //输出到文件夹
});
//压缩，合并 js
gulp.task("html", function() {
  return gulp
    .src("./client/*.html") //需要操作的文件
    .pipe(gulp.dest("./dist")); //输出到文件夹
});
//默认命令，在cmd中输入gulp后，执行的就是这个任务(压缩js需要在检查js之后操作)
gulp.task("default", ["jshint"], function() {
  gulp.start("minifyjs");
  gulp.start("minifycss");
  gulp.start("html");
  console.log("end");
});
